package cn.lizemin.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

/**
 * @author lzm
 * @Date 2024/7/27
 * @description 注意事项：每个servlet有自己独立的servlet配置，彼此之间互不影响
 * 这个servletConfig是Tomcat解析web.xml后，自动调用每个servlet的init(ServletConfig config)方法传进来的
 * 类似于spring的aware接口
 */
@WebServlet(urlPatterns = "/servlet6")
@MultipartConfig // 上传文件必须要使用这个注解才能够使用Part
public class MyServlet6 extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 读取文件，比如图片，excel等等
        Part part = req.getPart("wife");
        String path = getServletContext().getRealPath("upload");
        File uploadDir = new File(path);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        String fileName = part.getSubmittedFileName();
        System.out.println("old fileName：" + fileName);

        File destFile = new File(path, fileName);
        part.write(destFile.getAbsolutePath());
        System.out.println("upload file finished");

    }


}
